<?php
namespace backend\modules\admin\controllers;

use Yii;
use yii\helpers\Url;
use yii\data\ActiveDataProvider;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\modules\admin\models\Role;
use backend\modules\admin\models\RolePriv;
use backend\modules\admin\models\Menu;
use common\models\Tree;
use backend\modules\admin\models\Site;
use backend\modules\admin\models\Admin;
use yii\web\Response;
use backend\modules\admin\models\CategoryPriv;
use backend\modules\content\models\Category;

class RoleController extends Controller
{

    /**
     * role列表
     * 使用dateprovider自动分页
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Role::find()->where('status <> -1')->orderBy('roleid ASC'),
            'pagination' => [
                    'pageSize' => ADMINPAGENUM,
                ],
            'sort' => [
                'defaultOrder' => [
                    'listorder' => SORT_ASC,
                ]
            ],
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);

    }

    /**
     * 角色的数据库操作
     * 使用了AR类
     * 并添加了验证，如所需项为空，则添加失败
     */
    public function actionAddrole()
    {
        $model = new Role();
        $rs = [
            'url'=>'index',//跳转页面，若为goback,则返回上一页
            'msg'=>'添加失败',//跳转自定义信息
            'ms'=>5000,//延迟时间
            'msg_type'=>'error'//消息类型，success,error,close
        ];
        if($model->load(Yii::$app->request->post()))
        {
            if($model->validate())
            {
                $model->save(); 
                return $this->render('//msg',
                [
                    'url'=>'index',//跳转页面，若为goback,则返回上一页
                    'msg'=>'添加成功',//跳转自定义信息
                    'ms'=>5000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close
                ]);
            }
            else
            {
                return $this->render('//msg',$rs);
            }
            //return $this->redirect(['role/index']);
        }
        else
        {
            return $this->render('addrole', ['model' => $model]);
        }
    }

    /**
     * 删除role角色
     */
    public function actionDeleterole($roleid)
    {
        Yii::$app->response->format=Response::FORMAT_JSON;
        
        if($roleid==1)
        {
            return ['msg'=>'此角色不可删除','status'=>0];
        }

        $role = Role::findOne(['roleid' => $roleid]);

        $role->status = '-1';

        $res= $role->save();

        $role_priv = RolePriv::find()->where(['roleid'=>$roleid])->all();
        foreach($role_priv as $priv)
        {
            $priv->delete();
        }
        
        if($res){
            return ['msg'=>'删除成功','status'=>-1];
        }else{
            return ['msg'=>'删除失败','status'=>0];
        }
    }

    /**
     * 更改role角色显示状态
     */
    public function actionStatusrole($roleid)
    {
        Yii::$app->response->format=Response::FORMAT_JSON;
        
        $role = Role::findOne([
            'roleid' => $roleid,
            ]);
        //当角色为超级管理员时，不能禁用
        if($roleid==1)
        {
            return ['msg'=>'此角色不可禁用','status'=>0]; 
        }
        switch($role->status)
        {
            case 0:
                $role->status = '2';
                break;
            case 1:
                break;
            case 2:
                $role->status = '0';
                break;
        }
        $res= $role->save();

        
        if($res){
            return ['msg'=>'更改成功'];
        }else{
            return ['msg'=>'更改失败'];
        }
    }

    /**
     * 更改role角色
     */
    public function actionUpdaterole($roleid)
    {
        $role = Role::findOne(['roleid' => $roleid]);
        $rs = [
            'url'=>'index',//跳转页面，若为goback,则返回上一页
            'msg'=>'修改失败',//跳转自定义信息
            'ms'=>5000,//延迟时间
            'msg_type'=>'error'//消息类型，success,error,close
        ];
        if($role->load(Yii::$app->request->post()))
        {
            if($role->validate())
            {
                $role->save(); 
                return $this->render('//msg',
                [
                    'url'=>'index',//跳转页面，若为goback,则返回上一页
                    'msg'=>'修改成功',//跳转自定义信息
                    'ms'=>1000,//延迟时间
                    'msg_type'=>'success'//消息类型，success,error,close
                ]);
            }
            else
            {
                return $this->render('//msg',$rs);
            }
            //return $this->redirect(['role/index']);
        }
        else
        {
            return $this->render('updaterole',['role' => $role]);
        }
    }

    /**
     * 成员管理
     */
    public function actionRolemember($roleid)
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Admin::find()->where(['roleid'=>$roleid,'status'=>'0'])->orderBy(''),
            'pagination' => [
                'pageSize' => ADMINPAGENUM,
            ],
            'sort' => [
                'defaultOrder' => [
                    'userid' => SORT_ASC,

                ]
            ],
        ]);
        $roles = new Role();
        return $this->render('rolemember', [
            'dataProvider' => $dataProvider,
            'roles'=>$roles,
        ]);       
        
    }

    /**
     * 选择站点
     */
    public function actionSetsite($roleid)
    {
        $sites = Site::find()->where(['status'=>'0'])->all();
        return $this->renderAjax('setsite',['sites'=>$sites]);
    }
  
    /**
     * 角色权限
     */
    public function actionRolepriv($siteid,$roleid)
    {
        $menu = new Menu();
        
        if(Yii::$app->request->isPost)
        {
            //Yii::$app->response->format=Response::FORMAT_JSON;
            if(is_array(Yii::$app->request->post('menuid')) && count(Yii::$app->request->post('menuid'))>0)
            {
                
                $rolepriv = RolePriv::find('')->where(['roleid'=>$roleid,'siteid'=>$siteid])->all();
                foreach($rolepriv as $rol)
                {
                    $rol->delete();
                }
                $menuinfo = $menu->find('id','m','c','a','data')->all();
                foreach($menuinfo as $_v)
                {
                    $menu_info[$_v['id']] = $_v;
                }
                
                foreach(Yii::$app->request->post('menuid') as $menuid)
                {
                    $menuinfo = $menu->get_menuinfo(intval($menuid),$menu_info);
                    $role_priv = new RolePriv();
                    $role_priv->m = $menuinfo['m'];
                    $role_priv->c = $menuinfo['c'];
                    $role_priv->a = $menuinfo['a'];
                    $role_priv->data = $menuinfo['data'];
                    $role_priv->roleid = Yii::$app->request->get('roleid');
                    $role_priv->siteid = Yii::$app->request->get('siteid');
                    $role_priv->save();
                    
                }
            }
            else
            {
                $role_priv = new RolePriv();
                $role_priv->delete()->where(['roleid'=>Yii::$app->request->post('roleid'),'siteid'=>Yii::$app->request->post('siteid')]);
            }
            $this->layout=false;
            return $this->render('//msg',
            [
                'url'=>'',//跳转页面，若为goback,则返回上一页
                'msg'=>'修改成功',//跳转自定义信息
                'ms'=>5000,//延迟时间
                'msg_type'=>'success'//消息类型，success,error,close
            ]);
        }
        else
        {
            if($siteid)
            {
                $tree = new Tree();
                $tree->icon = array('│ ','├─ ','└─ ');
                $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
                $menu_all = Menu::find('')->asArray()->all();
                $priv_all = RolePriv::find('')->asArray()->all();
                foreach($menu_all as $key=>$cat)
                {
                    $menu_all[$key]['parentid_node']=$cat['parentid']?' class="child-of-node-'.$cat['parentid'].'"':'';
                    $menu_all[$key]['level']=Menu::get_level($cat['id'],$menu_all);
                    $menu_all[$key]['checked']=(Menu::is_checked($cat,$roleid,$siteid,$priv_all)) ? ' checked' : ''; 
                }
                $str  = "<tr id='node-\$id' \$parentid_node>
                            <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuid[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$cname</td>
                        </tr>";
                
                $menu=$tree->init($menu_all);
                $categorys = $tree->get_tree(0, $str);
                
                $sites = Site::find()->where(['status'=>'0'])->all();
                return $this->renderAjax('rolepriv',['categorys'=>$categorys,'sites'=>$sites]);
            }
        }
    }
    
    /**
     * 选择站点
     */
    public function actionSet($roleid)
    {
        $sites = Site::find()->where(['status'=>'0'])->all();
        return $this->renderAjax('set',['sites'=>$sites]);
    }

    /**
     * 角色的栏目权限
     */
    public function actionRolecatepriv($siteid,$roleid)
    {
        if(Yii::$app->request->isPost)
        {
            
            $catepriv = CategoryPriv::find()->where(['roleid'=>$roleid,'siteid'=>$siteid])->all();
            foreach($catepriv as $priv)
            {
                $priv->delete();
            }
            
            foreach(Yii::$app->request->post('priv') as $k=>$v)
            {
                if(is_array($v) && !empty($v[0]))
                {
                    foreach($v as $key=>$val)
                    {
                        $rolecatepriv = new CategoryPriv();
                        $rolecatepriv->siteid=$siteid;
                        $rolecatepriv->roleid=$roleid;
                        $rolecatepriv->catid=$k;
                        $rolecatepriv->action=$val;
                        $rolecatepriv->save();
                    }
                }
            }
            $this->layout=false;
            return $this->render('//msg',
            [
                'url'=>'',//跳转页面，若为goback,则返回上一页
                'msg'=>'修改成功',//跳转自定义信息
                'ms'=>5000,//延迟时间
                'msg_type'=>'success'//消息类型，success,error,close
            ]);

        }
        else
        {
            //获取站点栏目列表操作
            $category = Category::find()->asArray()->all();
            foreach($category as $k=>$v)
            {
                if (!in_array($v['type'], array(0,1))) unset($category[$k]);
            }
            //获取角色配置权限操作
            $data = CategoryPriv::find()->where(['roleid'=>$roleid,'siteid'=>$siteid])->asArray()->all();
            $priv = array();
            if($data)
            {
                foreach($data as $k=>$v)
                {
                    $priv[$v['catid']][$v['action']] = true;
                }
            }
            //生成树操作
            $tree = new Tree();
            $tree->icon = array('│ ','├─ ','└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            foreach($category as $k=>$v)
            {
                $v['id']=$v['catid'];
                
                if ($v['type'] == 1) {
					$v['disabled'] = 'disabled';
					$v['init_check'] = '';
					$v['add_check'] = '';
					$v['delete_check'] = '';
					$v['listorder_check'] = '';
					$v['push_check'] = '';
                    $v['move_check'] = '';
                    $v['edit_check'] = '';
				} else {
					$v['disabled'] = '';
					$v['add_check'] = isset($priv[$v['catid']]['add']) ? 'checked' : '';
					$v['delete_check'] = isset($priv[$v['catid']]['delete']) ? 'checked' : '';
					$v['listorder_check'] = isset($priv[$v['catid']]['listorder']) ? 'checked' : '';
					$v['push_check'] = isset($priv[$v['catid']]['push']) ? 'checked' : '';
					$v['move_check'] = isset($priv[$v['catid']]['remove']) ? 'checked' : '';
					$v['edit_check'] = isset($priv[$v['catid']]['edit']) ? 'checked' : '';
				}
				$v['init_check'] = isset($priv[$v['catid']]['init']) ? 'checked' : '';
				$category[$k] = $v;
            }
            
            
            $str =  "<tr>
                        <td align='center'><input type='checkbox'  value='1' onclick='select_all(\$catid, this)' ></td>
                        <td>\$spacer\$catname</td>
                        <td align='center'><input type='checkbox' name='priv[\$catid][]' \$init_check  value='init' ></td>
                        <td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$add_check value='add' ></td>
                        <td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$edit_check value='edit' ></td>
                        <td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$delete_check  value='delete' ></td>
                        <td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$listorder_check value='listorder' ></td>
                        <td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$push_check value='push' ></td>
                        <td align='center'><input type='checkbox' name='priv[\$catid][]' \$disabled \$move_check value='remove' ></td>
                    </tr>";
            
            $tree->init($category);
            
            $categorys = $tree->get_tree(0,$str);
            $sites = Site::find()->where(['status'=>'0'])->all();
            return $this->renderAjax('categorypriv',['categorys'=>$categorys,'sites'=>$sites]);
        }
    }
}
?>